package Client;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Listens for messages and sends them via Sockets PrintWriter.
 * 
 * @author PZK
 * 
 */
public class Sender extends Thread implements Runnable {

	private PrintWriter out;

	private List<String> messages = Collections
			.synchronizedList(new ArrayList<String>());

	public Sender(PrintWriter out) {
		System.out.println("Sender");
		this.out = out;

		start();

	}

	/**
	 * Used externally. Adds message to the queue and wakes up the thread.
	 * 
	 * @param message
	 */
	public synchronized void send(String message) {
                System.out.println("send: "+message);
		messages.add(message);
		notify();

	}

	/**
	 * Send message to the server using PrintWriter.
	 * 
	 * @param message
	 */
	private void sendToServer(String message) {

		out.println(message);
		out.flush();

	}

	/**
	 * 
	 * @return the next message from queue. Sleeps the thread if there are no
	 *         messages.
	 */
	private synchronized String nextMessage() {

		while (messages.size() == 0)
			try {
				wait();
			} catch (InterruptedException e) {

			}

		String message = messages.get(0);
		messages.remove(0);
		return message;

	}

	@Override
	public void run() {

		try {
			while (!isInterrupted()) {
				String message = nextMessage();
				sendToServer(message);
			}
		} catch (Exception e) {
			// disconnected from the server
		}
	}

}
